import CryptoJS from 'crypto-js'

export function encrypt(data, key) {
	// 生成随机IV（16字节）
	const iv = CryptoJS.lib.WordArray.random(16)
	// 转换密钥为WordArray
	const keyBytes = CryptoJS.enc.Utf8.parse(key)
	// 执行AES加密
	const encrypted = CryptoJS.AES.encrypt(data, keyBytes, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	})
	// 合并IV和密文并转换为Base64
	const combined = iv.concat(encrypted.ciphertext)
	return CryptoJS.enc.Base64.stringify(combined)
}

export function decrypt(combinedBase64, key) {
	// 解析Base64数据
	const combined = CryptoJS.enc.Base64.parse(combinedBase64)
	// 提取IV（前16字节）
	const iv = CryptoJS.lib.WordArray.create(combined.words.slice(0, 4)) // 4 words = 16 bytes
	// 提取密文
	const ciphertext = CryptoJS.lib.WordArray.create(combined.words.slice(4))
	const encrypted = CryptoJS.lib.CipherParams.create({
		ciphertext: ciphertext
	})
	// 转换密钥
	const keyBytes = CryptoJS.enc.Utf8.parse(key)
	// 执行解密
	const decrypted = CryptoJS.AES.decrypt(encrypted, keyBytes, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	})
	return decrypted.toString(CryptoJS.enc.Utf8)
}